<template>
	<template v-for="component in pageConfig" :key="component.id">
		<component :is="getComponent(component.id)" :data="component" :imgHost="imgHost"></component>
	</template>
	<tabbar :active="0"></tabbar>
</template>

<script setup>
	import { computed, ref, defineAsyncComponent, nextTick } from 'vue';
	import request from '@/utils/common/request/index';
	import { onPullDownRefresh, onReachBottom, onLoad } from '@dcloudio/uni-app';
	import tabbar from '@/components/tabbar/tabBar.vue';
	// #ifdef H5
	import { H5Login, h5DebugMode, setShareCard } from '@/utils/h5/index';
	// #endif
	import { usePageDecoration } from '@/store/modules/usePageDecoration.js';
	import { useGetThemColor } from '@/hooks/useGetThemColor';


	//使用到组件才会加载
	const swiper = defineAsyncComponent(() => import('@/components/decoration/swiper.vue'));
	const imageNav = defineAsyncComponent(() => import('@/components/decoration/image-nav.vue'));
	const navBar = defineAsyncComponent(() => import('@/components/decoration/nav-bar.vue'));
	const goodsNav = defineAsyncComponent(() => import('@/components/decoration/goods-nav.vue'));
	const goodsList = defineAsyncComponent(() => import('@/components/decoration/goods-list.vue'));
	const noticeBar = defineAsyncComponent(() => import('@/components/decoration/notice-bar.vue'));

	const { host, imgHost } = getApp().globalData;
	const { primaryColor } = useGetThemColor();

	// #ifdef H5
	// * 绑定上下级关系
	onLoad((options) => {
		const isDebug = options.debug;
		isDebug && h5DebugMode();

		const { super_user_id } = options;
		const token = uni.getStorageSync('token');

		if (super_user_id) {
			if (token) {
				request({
					url: '/api/superuser',
					method: 'POST',
					data: { super_user_id },
				}).then(() => {
					uni.showToast({
						title: '绑定关系成功',
					});
					history.replaceState({}, '', `/terminal/#/pages/home/home`);
				});
			} else {
				return uni.showModal({
					title: '提示',
					content: '请先授权登录',
					showCancel: false,
					confirmColor: primaryColor.value,
					success: function(res) {
						res.confirm && H5Login();
					},
				});
			}
		}
	});
	// #endif

	const pageDecoration = usePageDecoration();

	request({
		url: '/api/shopzdyzx',
		loadingTip: '加载中'
	}).then(res => {
		pageDecoration.setData(res);
	})

	const pageConfig = computed(() => {
		return pageDecoration.getPageConfig('home');
	})

	const getComponent = (id) => {
		const map = new Map([
			[1, swiper],
			[2, imageNav],
			[3, navBar],
			[5, goodsNav],
			[6, goodsList],
			[7, noticeBar],
		]);
		return map.get(id);
	}

	// #ifdef H5
	nextTick(() => {
		request({
			url: '/api/aboutuse?set_id=9',
		}).then(res => {
			const logoUrl = res.pic ? imgHost + res.pic : '/static/image/none-img.jpg';
			const getShareLink = () => {
				const shareLink = `${host}/terminal/#/pages/home/home`;
				return shareLink;
			};
			setShareCard('首页', '点击进入', getShareLink(), logoUrl)
		});
	})
	// #endif
</script>